using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Text.RegularExpressions;
using DMS.Business.Modules.Organization;
using DMS.Business.Modules.WorkFlow;

namespace DMS.BaseClass
{
	/// <summary>
	/// UISecurity.通过正则表达式设置控件的状态。现在可以控件的Enabled属性和Visible属性
	/// </summary>
	/// <remarks>
	/// 该整则表达式通过表单的ActionType,步骤名称StepName来判断的。
	/// (ActionType.StepName)该属性是否成立
    /// 通过设置ASP.NET控件的扩展属性EnableControl来设置控件在当前状态(ActionType)当前步骤（StepName）
	/// 下的Enabled属性，InVisibleControl来设置控件在什么状态，步骤下不可见。VisibleControl设置可见的状态和步骤。
	/// 如果VisibleControl和InVisibleControl属性冲突的话,VisibleControl属性优先。<br></br>
	/// 权限定义规则： (0.填写需求)(3.汇报审批)<br></br>
	/// 允许用*代表所有步骤，允许用9代表所有状态<br></br>
    /// 0=新建；1=修改；2=只读
	/// </remarks>
	/// <example>
	/// 下面例子控制“撤回”ImageButton在0（新建）1（可修改）的ActionType下不管任何步骤都不可见。而在任何状态任何步骤下<br></br>
	/// 都可用,当然这需要这个控件可见:)。
	/// <code>
	/// &lt; asp:ImageButton runat="server" BorderStyle="None" ImageUrl="/BMSSFlowWeb/Images/form_Rollback.gif"
	/// AlternateText="撤回" CssClass="ToobarImg" ID="ImgRollback" key="Rollback" InVisibleControl="(01.*)"
	/// EnableControl="(*.*)" &gt; &lt;/asp:ImageButton &gt;
	/// </code>
	/// </example>
	public class UISecurity
	{
		
		/// <summary>
		/// 设置controls数组内的控件的状态
		/// </summary>
		/// <param name="controls"></param>
		/// <param name="step">步骤名</param>
		/// <param name="actionType">ActionType</param>
		public static void SetSecurity( object[] controls , string step , int actionType)
		{
			string sEnable	= null ;
			string sInvisible = null;
			string sVisible	= null;
			string sDisable = null ;
            string sDisplay = null;
            string sInDisplay = null;

			bool bEnable ; 
			bool bInvisible;
			#region 根据步骤和动作判断域和按钮的显示
			foreach(object item in controls)
			{
				switch( item.GetType().BaseType.Namespace )
				{
					case "System.Web.UI.HtmlControls":
						sEnable  = ((HtmlControl)item).Attributes["EnableControl"];
						sDisable = ((HtmlControl)item).Attributes["DisableControl"];
						sInvisible = ((HtmlControl)item).Attributes["InvisibleControl"];
						sVisible	=	((HtmlControl)item).Attributes["VisibleControl"];
                        sDisplay = ((HtmlControl)item).Attributes["DisplayControl"];
                        sInDisplay = ((HtmlControl)item).Attributes["InDisplayControl"];
						break;
					case "System.Web.UI.WebControls":
						sEnable  = ((WebControl)item).Attributes["EnableControl"];
						sDisable = ((WebControl)item).Attributes["DisableControl"];
						sInvisible = ((WebControl)item).Attributes["InvisibleControl"];
						sVisible = ((WebControl)item).Attributes["VisibleControl"];
                        sDisplay = ((WebControl)item).Attributes["DisplayControl"];
                        sInDisplay = ((WebControl)item).Attributes["InDisplayControl"];
						break;
                    case "DMS.Web.Modules.UserControl":
						sEnable  = ((UserControl)item).Attributes["EnableControl"];
						sDisable = ((UserControl)item).Attributes["DisableControl"];
						sInvisible = ((UserControl)item).Attributes["InvisibleControl"];
						sVisible = ((UserControl)item).Attributes["VisibleControl"];
                        sDisplay = ((UserControl)item).Attributes["DisplayControl"];
                        sInDisplay = ((UserControl)item).Attributes["InDisplayControl"];
						break;
					default:
                         sDisplay = null;
                         sInDisplay = null;
						break;
				}

                // DisplayControl 优先级最高
                if (!string.IsNullOrEmpty(sDisplay)) {
                    bool display = CheckMatch(sDisplay, step, actionType);
                    if (display) {
                        ((HtmlControl)item).Style[HtmlTextWriterStyle.Display] = "block";
                    } else {
                        ((HtmlControl)item).Style[HtmlTextWriterStyle.Display] = "none";
                    }
                    continue;
                }
                // InDisplayControl 
                if (!string.IsNullOrEmpty(sInDisplay)) {
                    bool display = !CheckMatch(sInDisplay, step, actionType);
                    if (display) {
                        ((HtmlControl)item).Style[HtmlTextWriterStyle.Display] = "block";
                    } else {
                        ((HtmlControl)item).Style[HtmlTextWriterStyle.Display] = "none";
                    }
                    continue;
                }
				bEnable = CheckMatch( sEnable , step , actionType );

				switch( item.GetType().BaseType.Namespace )
				{
					case "System.Web.UI.HtmlControls":
						((HtmlControl)item).Disabled = !bEnable;
						break;
					case "System.Web.UI.WebControls":
						if( item.GetType().Equals(typeof(TextBox)) )
						{
							TextBox tb = (TextBox)item;
							tb.ReadOnly = !bEnable;
                            //时间控件去掉class
                            if (!bEnable && tb.Attributes["class"] == "txt_calendar")
                                tb.Attributes["class"] = "";
						}
						else
						{
							((WebControl)item).Enabled = bEnable;
						}
						break;
                    case "DMS.Web.Modules.UserControl":
						//((TextBox)((UserControl)item).FindControl("CurrOpinion")).Enabled = bEnable;
                        //((UserControl)item).Enabled = bEnable;
						break;
					default:
						break;
				}

				bEnable = CheckMatch( sEnable , step , actionType );

				//不可用控制比可用控制优先(注意：在可用的前提下过滤不可用的) 
				if (sDisable!=null&&bEnable)
					bEnable = !CheckMatch( sDisable , step , actionType );
				
				bInvisible = CheckMatch ( sInvisible , step , actionType);
				//可见控制必不可见控制优先！

                if (sVisible != null) {
                    bInvisible = !CheckMatch(sVisible, step, actionType);
                }
                try {
                    // 部分非可视控件不支持该属性
                    ((Control)item).Visible = !bInvisible;
                } catch (Exception) {   }
                    

                
				
			}
			#endregion
		}

        //public static void SetWorkflowSecurity(object[] controls, string step, int actionType,string instanceId, string workitemId, WorkFlowInstance instance, User currentUser) {
        //    string sEnable = null;
        //    string sInvisible = null;
        //    string sVisible = null;
        //    string sDisable = null;
        //    string sDisplay = null;
        //    string sInDisplay = null;

        //    bool bEnable;
        //    bool bInvisible;

        //    #region 根据步骤和动作判断域和按钮的显示
        //    foreach (object item in controls) {



        //        switch (item.GetType().BaseType.Namespace) {
        //            case "System.Web.UI.HtmlControls":
        //                sEnable = ((HtmlControl)item).Attributes["EnableControl"];
        //                sDisable = ((HtmlControl)item).Attributes["DisableControl"];
        //                sInvisible = ((HtmlControl)item).Attributes["InvisibleControl"];
        //                sVisible = ((HtmlControl)item).Attributes["VisibleControl"];
        //                sDisplay = ((HtmlControl)item).Attributes["DisplayControl"];
        //                sInDisplay = ((HtmlControl)item).Attributes["InDisplayControl"];
        //                break;
        //            case "System.Web.UI.WebControls":
        //                sEnable = ((WebControl)item).Attributes["EnableControl"];
        //                sDisable = ((WebControl)item).Attributes["DisableControl"];
        //                sInvisible = ((WebControl)item).Attributes["InvisibleControl"];
        //                sVisible = ((WebControl)item).Attributes["VisibleControl"];
        //                sDisplay = ((WebControl)item).Attributes["DisplayControl"];
        //                sInDisplay = ((WebControl)item).Attributes["InDisplayControl"];
        //                break;
        //            case "DMS.Web.Modules.UserControl":
        //                sEnable = ((UserControl)item).Attributes["EnableControl"];
        //                sDisable = ((UserControl)item).Attributes["DisableControl"];
        //                sInvisible = ((UserControl)item).Attributes["InvisibleControl"];
        //                sVisible = ((UserControl)item).Attributes["VisibleControl"];
        //                sDisplay = ((UserControl)item).Attributes["DisplayControl"];
        //                sInDisplay = ((UserControl)item).Attributes["InDisplayControl"];
        //                break;
        //            default:
        //                sDisplay = null;
        //                sInDisplay = null;
        //                break;
        //        }

        //        // DisplayControl 优先级最高
        //        if (!string.IsNullOrEmpty(sDisplay)) {
        //            bool display = CheckMatch(sDisplay, step, actionType);
        //            if (display) {
        //                ((HtmlControl)item).Style[HtmlTextWriterStyle.Display] = "block";
        //            } else {
        //                ((HtmlControl)item).Style[HtmlTextWriterStyle.Display] = "none";
        //            }
        //            continue;
        //        }
        //        // InDisplayControl 
        //        if (!string.IsNullOrEmpty(sInDisplay)) {
        //            bool display = !CheckMatch(sInDisplay, step, actionType);
        //            if (display) {
        //                ((HtmlControl)item).Style[HtmlTextWriterStyle.Display] = "block";
        //            } else {
        //                ((HtmlControl)item).Style[HtmlTextWriterStyle.Display] = "none";
        //            }
        //            continue;
        //        }
        //        bEnable = CheckMatch(sEnable, step, actionType);

        //        switch (item.GetType().BaseType.Namespace) {
        //            case "System.Web.UI.HtmlControls":
        //                ((HtmlControl)item).Disabled = !bEnable;
        //                break;
        //            case "System.Web.UI.WebControls":
        //                if (item.GetType().Equals(typeof(TextBox))) {
        //                    TextBox tb = (TextBox)item;
        //                    tb.ReadOnly = !bEnable;
        //                    //时间控件去掉class
        //                    if (!bEnable && tb.Attributes["class"] == "txt_calendar")
        //                        tb.Attributes["class"] = "";
        //                } else {
        //                    ((WebControl)item).Enabled = bEnable;
        //                }
        //                break;
        //            case "DMS.Web.Modules.UserControl":
        //                //((TextBox)((UserControl)item).FindControl("CurrOpinion")).Enabled = bEnable;
        //                //((UserControl)item).Enabled = bEnable;
        //                break;
        //            default:
        //                break;
        //        }

        //        bEnable = CheckMatch(sEnable, step, actionType);

        //        //不可用控制比可用控制优先(注意：在可用的前提下过滤不可用的) 
        //        if (sDisable != null && bEnable)
        //            bEnable = !CheckMatch(sDisable, step, actionType);

        //        bInvisible = CheckMatch(sInvisible, step, actionType);
        //        //可见控制必不可见控制优先！

        //        if (sVisible != null) {
        //            bInvisible = !CheckMatch(sVisible, step, actionType);
        //        }
        //        try {
        //            // 部分非可视控件不支持该属性
        //            ((Control)item).Visible = !bInvisible;
        //        } catch (Exception) { }




        //    }
        //    #endregion
        //}

        public static bool CheckMatch(object control, string step, int actionType) {
            return true;
        }

		internal static bool CheckMatch( string sTag , string step , int actionType)
		{
			if ( sTag == null || sTag.Length == 0) return false;

			// 权限定义规则： (0.填写需求)(3:汇报审批)
			// 允许用*代表所有步骤，允许用9代表所有状态
			Regex regex = new Regex(@"\((?<digit>[0-4,\*]+).(?<step>[^)]+)\)"); 
			MatchCollection mc = regex.Matches(sTag);

			// 如果步骤名称一样，并且包含指定的动作
			foreach (Match m in mc) 
				if  (( m.Groups["step"].Value.Equals(step) || m.Groups["step"].Value.Equals("*") ) && 
					(m.Groups["digit"].Value.IndexOf( actionType.ToString() ) >=0 || m.Groups["digit"].Value.Equals("*")))
					return true;

			return false;
		}
		
		private static void ProcessValidation ( object item )
		{
			Type type = item.GetType();
			if ( type.Equals( typeof(RequiredFieldValidator) ) )
			{
				RequiredFieldValidator req = (RequiredFieldValidator)item;
				object compare = req.FindControl(req.ControlToValidate) as WebControl ;
				if ( compare == null)
					req.Enabled = !((HtmlControl)item).Disabled;
				else
					req.Enabled = ((WebControl)item).Enabled;
			}
		}
	}
}
